package commands;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;

import database.models.MessageOwnerModel;
import database.models.TagModel;

import twitter4j.internal.org.json.JSONArray;
import twitter4j.internal.org.json.JSONException;
import twitter4j.internal.org.json.JSONObject;

/**
 * Command that gets the top 10 tags from the database.
 * 
 * @author Project group 9
 * 
 */
public class GetTopOwnersCommand implements Command {
	JSONObject jsonObject;
	MessageOwnerModel messageOwnerModel;

	public GetTopOwnersCommand(JSONObject jsonObject, MessageOwnerModel messageOwnerModel) {
		this.jsonObject = jsonObject;
		this.messageOwnerModel = messageOwnerModel;
	}

	public String execute() throws JSONException {
		JSONArray sendArray = new JSONArray();
		JSONObject parameters = jsonObject.getJSONObject("getTopOwners");
		int amount = (parameters.isNull("amount")) ? 10 : parameters.getInt("amount");
		
		ArrayList<HashMap<String, String>> topOwners = (parameters.isNull("keywords")) ? messageOwnerModel.getTopOwners(amount, null) : messageOwnerModel.getTopOwners(amount, parameters.getJSONArray("keywords"));
		
		for (HashMap<String, String> owner : topOwners) {
			Iterator<String> iterator = owner.keySet().iterator();
			
			JSONObject arrayObject = new JSONObject();
			
			while(iterator.hasNext()) {
				JSONObject object = new JSONObject();
				object.put("count", owner.get(iterator.next()));
				object.put("account", owner.get(iterator.next()));
				arrayObject.put("listItem", object);
			}
			sendArray.put(arrayObject);
		}
		return sendArray.toString();
	}
}
